//
//  AddCreditCardViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/3/12.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "AddCreditCardViewController.h"
#import "AddCreditTableViewCell.h"
#import "AddcreditCardHeaderView.h"
#import "AddCreditCardModelPack.h"
#import "BankListView.h"
#import "BankListModelPack.h"
#import "RSA.h"
#import <UIImageView+WebCache.h>
#import "BankListTableViewCell.h"
@interface AddCreditCardViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate>
//搜索框
@property (strong, nonatomic) UISearchController *searchController;

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *creditInfoArray;
@property(nonatomic,strong)NSMutableArray *creditInfoValueArray;
@property(nonatomic,strong)UIButton *nextStypeBtn;


@property(nonatomic,strong)UITextField *nameTf;
@property(nonatomic,strong)UITextField *bankPhoneTf;
@property(nonatomic,strong)UITextField *bankCardNumTf;
@property(nonatomic,strong)UITextField *bankNameTf;
@property(nonatomic,strong)UITextField *bankCVN2Tf;
@property(nonatomic,strong)UITextField *validityTf;

//银行卡简称
@property(nonatomic,strong)NSString *banIdStr;


//弹出银行名称
@property(nonatomic,strong)BankListView *bv;
//银行名称模型数组
@property(nonatomic,strong)NSMutableArray *bankNameArray;

/**
 键盘上方的完成
 */
@property(nonatomic,strong)UIToolbar *toolbar;



@end

@implementation AddCreditCardViewController

-(NSMutableArray *)bankNameArray
{
    if (_bankNameArray == nil) {
        _bankNameArray = [NSMutableArray array];
    }
    return _bankNameArray;
}

-(NSMutableArray *)creditInfoArray
{
    if (_creditInfoArray == nil) {
        _creditInfoArray = [NSMutableArray array];
    }
    return _creditInfoArray;
}

-(NSMutableArray *)creditInfoValueArray
{
    if (_creditInfoValueArray == nil) {
        _creditInfoValueArray = [NSMutableArray array];
    }
    return _creditInfoValueArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加信用卡";
    self.view.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:244 / 255.0 blue:246 / 255.0 alpha:1];
    [self createTableView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    //提交
    [self createNextStype];
    //创建搜索框
    
}
#pragma mark  键盘回收
-(void)keyboardHide:(NSNotification *)note
{
   self.tableView.contentInset = UIEdgeInsetsZero;
}
#pragma mark  键盘弹出
-(void)keyboardShow:(NSNotification *)note
{
    CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.tableView.contentInset= UIEdgeInsetsMake(0,0, keyBoardRect.size.height,0);
}


-(void)createNextStype
{
    self.nextStypeBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.nextStypeBtn.backgroundColor = [UIColor colorWithRed:91 / 255.0 green:113 / 255.0 blue:255 / 255.9 alpha:1];
    [self.nextStypeBtn setTitle:@"提交" forState:(UIControlStateNormal)];
    [self.nextStypeBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    self.nextStypeBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    self.nextStypeBtn.frame = CGRectMake(0, self.view.frame.size.height - ETTopHeight - ETTabBarArcHeight - 44, self.view.frame.size.width, 44);
    [self.view addSubview:self.nextStypeBtn];
    [self.nextStypeBtn addTarget:self action:@selector(submitBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
}
-(void)submitBtnAction
{
    NSLog(@"点击提交");
    if (self.bankCardNumTf.text.length == 0) {
        [self showFailedResultTips:@"请输入银行卡号" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    if (self.bankPhoneTf.text.length == 0) {
        [self showFailedResultTips:@"请输入预留手机号" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    if (self.bankNameTf.text.length == 0) {
        [self showFailedResultTips:@"请选择开户行网点" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    if (self.bankCVN2Tf.text.length == 0) {
        [self showFailedResultTips:@"请输入CVN2" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    if (self.validityTf.text.length == 0) {
        [self showFailedResultTips:@"请输入有效期" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    
    
    AddCreditCardRequest *request = [[AddCreditCardRequest alloc] init];
    request.cardNo = [RSA encryptString:self.bankCardNumTf.text publicKey:ETPublicKeyStr];
    request.bankName = self.bankNameTf.text;
    request.bankId = self.banIdStr;
    request.cvnNo = [RSA encryptString:self.bankCVN2Tf.text publicKey:ETPublicKeyStr];
    request.cardExpiryDate = [RSA encryptString:self.validityTf.text publicKey:ETPublicKeyStr];
    request.leftPhone = [RSA encryptString:self.bankPhoneTf.text publicKey:ETPublicKeyStr];
    NSDictionary *dic = [request mj_keyValues];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/creditCard/addCreditCard"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self dealAddCreditCard:responseObject];
            });
        }
        
    } FailedHandler:^(NSError *error) {
        
    }];
}
-(void)dealAddCreditCard:(id)responseObject
{
    //绑卡成功，返回
    AddCreditCardResponse *addCreditCardResponse = [AddCreditCardResponse mj_objectWithKeyValues:responseObject];
    NSString *creditId = addCreditCardResponse.response.creditId;
    NSString *bankCode = addCreditCardResponse.response.bankId;
    
    
    //支付卡+1
    NSInteger num = [[AppTools shareInstance].userInfo.creditCardNum integerValue] + 1;
    [AppTools shareInstance].userInfo.creditCardNum = [NSString stringWithFormat:@"%ld",(long)num];
    
    /*
    //把登录返回的数据模型存储到本地
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[AppTools shareInstance].userInfo];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"u"];
    */
    
    
    //绑卡成功之后block回调  根据id查询费率和秒到时间
    if (self.returnValueBlock) {
        self.returnValueBlock(creditId, self.bankNameTf.text, self.bankPhoneTf.text,self.bankCardNumTf.text,bankCode);
    }
    
    //绑卡成功之后block回调  重新查询卡列表
    if (self.refreshCreditCardBlock) {
        self.refreshCreditCardBlock();
    }
    
    [self showSuccessResultTips:@"绑卡成功" animated:YES forSeconds:SUCCESS_SHOW_TIME_DEF completionBlock:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

-(void)createTableView
{
    self.creditInfoArray = @[@"持卡人姓名",@"银行卡号",@"预留手机号",@"开户银行",@"CVN2",@"有效期"].mutableCopy;
    self.creditInfoValueArray = @[@"请输入持卡人姓名(实名认证的名字)",@"16位银行卡号(需为信用卡)",@"银行卡预留手机号",@"选择开户银行",@"银行卡背面末3位数字",@"示例:09/20,请输入0920"].mutableCopy;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - ETTopHeight - ETTabBarArcHeight - 44) style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = ETColorWithRGB(242, 244, 246);
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesturedDetected1:)];
    tapGesture.delegate = self;
    [self.tableView addGestureRecognizer:tapGesture];
    [self.tableView registerClass:[AddCreditTableViewCell class] forCellReuseIdentifier:@"cell"];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return self.creditInfoArray.count;
    }else
    {
        return self.bankNameArray.count;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        AddCreditTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleLab.text = self.creditInfoArray[indexPath.row];
        cell.titleValueTf.placeholder = self.creditInfoValueArray[indexPath.row];
        //最后一个cell不显示分割线
        if (indexPath.row == self.creditInfoArray.count - 1) {
            cell.lineView.hidden = YES;
        }
        //选择开户网点
        if (indexPath.row == 3) {
            cell.titleValueTf.userInteractionEnabled = NO;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
        
        if (indexPath.row == 0) {
            self.nameTf = cell.titleValueTf;
            self.nameTf.text = [AppTools shareInstance].userInfo.userName;
            self.nameTf.userInteractionEnabled = NO;
        }
        if (indexPath.row == 1) {
            self.bankCardNumTf = cell.titleValueTf;
            self.bankCardNumTf.delegate = self;
        }
        if (indexPath.row == 2) {
            self.bankPhoneTf = cell.titleValueTf;
        }
        if (indexPath.row == 3) {
            self.bankNameTf = cell.titleValueTf;
        }
        if (indexPath.row == 4) {
            self.bankCVN2Tf = cell.titleValueTf;
        }
        if (indexPath.row == 5) {
            self.validityTf = cell.titleValueTf;
        }
        
        //输入框都是纯数字    增加完成
        cell.titleValueTf.keyboardType = UIKeyboardTypeNumberPad;
        cell.titleValueTf.inputAccessoryView = [self addToolbar];
        cell.titleValueTf.delegate = self;
        [cell.titleValueTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
        return cell;
        
    }else
    {
        BankListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bankListCell" forIndexPath:indexPath];
        BankListRecord *record = self.bankNameArray[indexPath.row];
        [cell.iconImv sd_setImageWithURL:[NSURL URLWithString:record.bankIcon] placeholderImage:[UIImage imageNamed:@"logo_yinhang"]];
        cell.titleLab.text = record.text;
        return cell;
    }
}
-(void)textFieldDidChange :(UITextField *)textField{
    
    //CVN2码只能输入3位
    if (textField == self.bankCVN2Tf) {
        if (textField.text.length > 3) {
            textField.text = [textField.text substringToIndex:3];
        }
    }
    
    //有效期只能输入4位
    if (textField == self.validityTf) {
        if (textField.text.length > 4) {
            textField.text = [textField.text substringToIndex:4];
        }
    }
    //手机号输入框只能输入11位
    if (textField == self.bankPhoneTf) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    //当银行卡号失去焦点时,请求后端的银行
    if (textField == self.bankCardNumTf && self.bankCardNumTf.text.length != 0) {
        [self getBankListWithCardNum:self.bankCardNumTf.text];
    }
}

//数字键盘加完成按钮
- (UIToolbar *)addToolbar
{
    self.toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 40)];
    self.toolbar.backgroundColor = ETColorWithRGB(232, 232, 232);
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    btn.backgroundColor = [UIColor whiteColor];
    [btn setTitle:@"完成" forState:(UIControlStateNormal)];
    [btn setTitleColor:ETColorWithRGB(0, 0, 0) forState:(UIControlStateNormal)];
    btn.layer.borderColor = ETColorWithRGB(0, 0, 0).CGColor;
    btn.layer.borderWidth = 1;
    btn.layer.cornerRadius = 4;
    btn.frame = CGRectMake(0, 0, 76, 28);
    [btn addTarget:self action:@selector(textFieldDone) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.toolbar.items = @[space, bar];
    return self.toolbar;
}
-(void)textFieldDone
{
    [self.view endEditing:YES];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        
            AddCreditTableViewCell *cell = (AddCreditTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
            [cell.titleValueTf becomeFirstResponder];
            
        if (indexPath.row == 3) {
            [self.view endEditing:YES];
            //选择开户行
            [self getBankListWithCardNum:@""];
            self.tableView.userInteractionEnabled = NO;
        }
    }else
    {
        BankListRecord *record = self.bankNameArray[indexPath.row];
        self.bankNameTf.text = record.text;
        self.banIdStr = record.value;
        [self BankListViewdismiss];
    }
    
    
}
-(void)getBankListWithCardNum:(NSString *)cardNum
{
    
    if (cardNum.length != 0) {
        [self NoTipsNetWithCardNum:cardNum];
    }else
    {
        [self TipsNetWithCardNum];
    }
    
}

//无提示框请求银行列表
-(void)NoTipsNetWithCardNum:(NSString *)cardNum
{
    BankListRequest *request = [[BankListRequest alloc] init];
    request.cardNo = cardNum;
    NSDictionary *dic = [request mj_keyValues];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/bankCard/getBankByCardNo"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOSTNOTips:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self dealbankListWithResponse:responseObject];
            });
        }else
        {
            self.bankNameTf.text = @"";
            self.tableView.userInteractionEnabled = YES;
            
        }
    } FailedHandler:^(NSError *error) {
        
        self.tableView.userInteractionEnabled = YES;
        
    }];
}
//有提示框请求银行列表
-(void)TipsNetWithCardNum
{
    BankListRequest *request = [[BankListRequest alloc] init];
    request.cardNo = @"";
    NSDictionary *dic = [request mj_keyValues];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/bankCard/getBankByCardNo"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self dealbankListWithResponse:responseObject];
            });
        }else
        {
            self.bankNameTf.text = @"";
            self.tableView.userInteractionEnabled = YES;
        }
    } FailedHandler:^(NSError *error) {
        
        self.tableView.userInteractionEnabled = YES;
        
    }];
}


-(void)dealbankListWithResponse:(id )responseObject
{
    self.bv.bankListTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ETScreenW, 0.0001f)];
    self.bv.bankListTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ETScreenW, 0.0001f)];
    BankListResponse *bankListResponse = [BankListResponse mj_objectWithKeyValues:responseObject];
    NSLog(@"%@",bankListResponse);
    
    if (bankListResponse.response.bankList.count == 1) {
        //输入框赋值
        BankListRecord *record = bankListResponse.response.bankList[0];
        self.bankNameTf.text = record.text;
        self.banIdStr = record.value;
    }else
    {
        [self popBanList];
        
        
        [self.bv.offBtn addTarget:self action:@selector(offBtnAction) forControlEvents:(UIControlEventTouchDown)];
        [self.bankNameArray removeAllObjects];
        for (BankListRecord *record in bankListResponse.response.bankList) {
            //存储到数组,点击时直接取数据
            [self.bankNameArray addObject:record];
        }
        [self.bv.bankListTableView reloadData];
        NSLog(@"%@",self.bankNameArray);
    }
}
-(void)offBtnAction
{
    [self BankListViewdismiss];
}
-(void)popBanList
{
    self.bv = [[BankListView alloc] initWithFrame:(CGRectMake(0, ETScreenH, ETScreenW, 400))];
    AppDelegate *delegate  = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate.window addSubview:self.bv];
    
    
    //给弹出框加上点击事件  响应底部弹窗消失
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesturedDetected:)];
    tapGesture.delegate = self;
    [self.bv addGestureRecognizer:tapGesture];
    
    
    
    
    __weak AddCreditCardViewController *weakSelf = self;
    self.bv.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    [UIView animateWithDuration:0.5 animations:^{
        [weakSelf.bv setFrame:CGRectMake(0, 0, ETScreenW, ETScreenH)];
    } completion:^(BOOL finished) {
        self.tableView.userInteractionEnabled = YES;
        weakSelf.bv.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    }];
    
    self.bv.bankListTableView.delegate = self;
    self.bv.bankListTableView.dataSource = self;
    self.bv.bankListTableView.userInteractionEnabled = YES;
    self.bv.bankListTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ETScreenW, 0.0001f)];
    self.bv.bankListTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ETScreenW, 0.0001f)];
    [self.bv.bankListTableView registerClass:[BankListTableViewCell class] forCellReuseIdentifier:@"bankListCell"];
}





-(void)tapGesturedDetected:(UIGestureRecognizer *)tap
{
    CGPoint point = [tap locationInView:self.bv];
    
    if (point.y < ETScreenH - 400) {
        self.bv.backgroundColor = [UIColor clearColor];
        __weak BankListView *weakSelf = self.bv;
        [UIView animateWithDuration:0.5 animations:^{
            weakSelf.frame = CGRectMake(0, ETScreenH, ETScreenW, ETScreenH);
        } completion:^(BOOL finished) {
            
        }];
    }
}

-(void)BankListViewdismiss
{
    self.bv.backgroundColor = [UIColor clearColor];
    __weak BankListView *weakSelf = self.bv;
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.frame = CGRectMake(0, ETScreenH, ETScreenW, ETScreenH);
    } completion:^(BOOL finished) {
        
    }];
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        AddcreditCardHeaderView *headerView = [[AddcreditCardHeaderView alloc] init];
        headerView.tipsLab.text = @"填写信用卡信息";
        return headerView;
    }else
    {
        return nil;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        return 70;
    }else
    {
        return 50;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return 64;
    }else
    {
        return 0.01f;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}



-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.01)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(nonnull UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//如果当前是tableView
        //做自己想做的事
        return NO;
    }
    return YES;
}

-(void)tapGesturedDetected1:(UIGestureRecognizer *)tap
{
    [self.view endEditing:YES];
}

-(void)dealloc
{
    [self.bv removeFromSuperview];
    [self.toolbar removeFromSuperview];
}


@end
